package com.kk.utils;

import com.kk.pojo.dto.LoginUser;
import com.kk.pojo.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;

import java.math.BigInteger;

/**
 * Security Context工具类
 * 用于获取当前登录用户信息，避免前端传递用户ID带来的安全风险
 *
 * @author kl
 * @version 1.0
 * @date 2025/10/15
 */
@Slf4j
public class SecurityUtils {

    /**
     * 获取当前登录用户的用户名
     *
     * @return 用户名，如果未登录返回null
     */
    public static String getCurrentUsername() {
        try {
            Authentication authentication = getAuthentication();
            if (authentication != null && authentication.getPrincipal() != null) {
                Object principal = authentication.getPrincipal();

                if (principal instanceof UserDetails) {
                    return ((UserDetails) principal).getUsername();
                } else if (principal instanceof String) {
                    return (String) principal;
                }
            }
        } catch (Exception e) {
            log.error("获取当前用户名失败", e);
        }
        return null;
    }

    /**
     * 获取当前登录用户完整信息
     */
    public static LoginUser getLoginUser() {
        try {
            Authentication authentication = getAuthentication();
            if (authentication != null && authentication.getPrincipal() instanceof LoginUser) {
                return (LoginUser) authentication.getPrincipal();
            }
        } catch (Exception e) {
            log.error("获取当前登录用户失败", e);
        }
        return null;
    }

    /**
     * 获取当前登录用户的用户ID
     * 从JWT token的claims中获取
     *
     * @return 用户ID，如果未登录返回null
     */
    public static BigInteger getCurrentUserId() {
        try {
            Authentication authentication = getAuthentication();
            if (authentication != null && authentication.getPrincipal() != null) {
                Object principal = authentication.getPrincipal();

                // ✅ 从 principal 获取（标准做法）
                if (principal instanceof LoginUser) {
                    return ((LoginUser) principal).getUserId();
                }
            }
        } catch (Exception e) {
            log.error("获取当前用户ID失败", e);
        }
        return null;
    }

    /**
     * 获取当前Authentication对象
     *
     * @return Authentication对象
     */
    public static Authentication getAuthentication() {
        SecurityContext context = org.springframework.security.core.context.SecurityContextHolder.getContext();
        return context != null ? context.getAuthentication() : null;
    }

    /**
     * 判断当前用户是否已认证
     *
     * @return true-已认证，false-未认证
     */
    public static boolean isAuthenticated() {
        Authentication authentication = getAuthentication();
        return authentication != null &&
                authentication.isAuthenticated() &&
                !(authentication.getPrincipal() instanceof String &&
                        "anonymousUser".equals(authentication.getPrincipal()));
    }

    /**
     * 获取当前用户的UserDetails
     *
     * @return UserDetails对象，如果未登录返回null
     */
    public static UserDetails getCurrentUserDetails() {
        try {
            Authentication authentication = getAuthentication();
            if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
                return (UserDetails) authentication.getPrincipal();
            }
        } catch (Exception e) {
            log.error("获取当前UserDetails失败", e);
        }
        return null;
    }

    /**
     * 清除当前用户的认证信息（用于登出）
     */
    public static void clearAuthentication() {
        org.springframework.security.core.context.SecurityContextHolder.clearContext();
    }
}
